package com.eschool.beans.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.eschool.dao.CourseDao;
import com.eschool.dao.SessionDao;
import com.eschool.model.Course;
import com.eschool.model.Session;


public class SessionConverter implements Converter {

    public static List<com.eschool.model.Session> sessionDB;

    static {
    			sessionDB = new ArrayList<com.eschool.model.Session>();
    			sessionDB = SessionDao.getSessions(null);
    }

    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                for (com.eschool.model.Session s : sessionDB) {
                    if (s.getSessionTitle().equalsIgnoreCase(submittedValue)) {
                        return s;
                    }
                }
                
            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Session"));
            }
        }

        return null;
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return ((com.eschool.model.Session) value).getSessionTitle();
        }
    }
}
